/*
 * ***** BEGIN LICENSE BLOCK *****
 * This file is part of "myWiWall".
 * Copyright (c) 2007-2008 CRP Henri Tudor and contributors.
 * All rights reserved.
 *
 * "myWiWall" is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as published by
 * the Free Software Foundation.
 * 
 * "myWiWall" is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with "myWiWall"; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * ***** END LICENSE BLOCK *****
 */


	/* addWidget takes as argument a widgetId and calls the requestManifest method of the widgetFactory */
	function addWidget(widget)
	{
		try {
			$.ajax({
				data: 'widgetId=' + widget,
				dataType: 'json',
				success: function(data) {
					
					if (data == false || (data == true && confirm(I18n.__("This widget may disclose personnal information to trusted web services. Are you sure that you want to use it ?"))))
					{
						widgetFactory.requestManifest(widget, {
							requiresSync: true
						});
					}
				},
				error: function(xhr, msg, type){
					notify(xhr.statusText);
				},
				type: 'GET',
				url: '../../index.php/engine/isUsingAuthentication'
			});
		} catch (e)
		{
			debug(e);
		}
		
		
	}

	/* load the user interface and request the manifest for each widget */
	function loadInterface()
	{

		$.ajax({
			type: "GET",
			url: "../../index.php/engine/getInterface",
			data: "format=json",
			dataType: "json",
			success: function(widgets){
				
				for(var i = 0; i < widgets.length; i++)
				{
					var widget = widgets[i];
					
					/* no synchronization is needed, the widgets already exist in the user interface */
					widgetFactory.requestManifest(widget.name, {
						col: widget.column,
						minimized: widget.minimized,
						requiresSync: false
					});
				}
			},
			error: function(xhr, msg, type){
				debug(xhr.statusText);
			}
		});
	}
	
	/* synchronize the local interface with the server */
	function updateInterface(serial, action, widget)
	{	
		var serialString = '';
		
		if (serial)
		{
			for (var i = 0; i < serial.length; i++)
			{
				if (serial[i] != '')
					serialString += '&' + serial[i].hash;
			}
		}
		
		var data;
		if (widget != undefined)
			data = 'widgetId=' + widget + '&action=' + action + serialString;
		else
			data = 'action=' + action + serialString;

		$.ajax({
			type: "POST",
			url: "../../index.php/engine/updateInterface",
			data: data,
			dataType: 'html',
			success: function(text){
				/* possibility to add an event when the interface has been updated successfully */
				//debug(text);
			},
			error: function(xhr, msg, type){
				debug(xhr.statusText);
			}
		});
	}
	
	/* synchronize the preferences of a widget with the server */
	function updatePreferences(widgetId)
	{
		data = {'widgetId': widgetId, 'widgetTags': document.getElementById('tagInput_'+widgetId).value};
		
		$('#editForm_'+widgetId + ' :input').each(function()
		{

			if (this.type == 'submit' || this.type == 'reset' || this.id == ('tagInput_' + widgetId))
				return;
				
			var pref = this.name.substr(10 + widgetId.length);
			var val = this.value;
			
			data[pref] = this.value;
			widgetFactory.widgets[widgetId].manifest['preferences'][pref]['value'] = this.value;
		});

		/*  hide the edit preferences window */
		widgetFactory.widgets[widgetId].edit();
		
		/* reload the iframe */
		if (widgetFactory.widgets[widgetId].manifest['widget_type'] == 'local')
			document.getElementById('iframe_' + widgetId).contentWindow.location.reload();
		else
		{
			params = widgetFactory.widgets[widgetId].getRemotePreferences();
			document.getElementById('iframe_' + widgetId).src = widgetFactory.widgets[widgetId].manifest['widget_location']	+ '?' + params;
		}
		
		/* synchronize preferences with server */
		$.ajax({
			type: "POST",
			url: "../../index.php/engine/updatePreferences",
			data: data,
			dataType: 'html',
			success: function(text){
				/* possibility to add an event when the preferences have been saved */
				//debug(text);
			},
			error: function(xhr, msg, type){
				debug(xhr.statusText);
			}
		});
	}
	
	function toggleLoading()
	{
		$('#loading').slideToggle('slow', function(){
			$('#menu').toggle();
		});	
	}
	
	function getPortalBaseURI()
	{
		return window.portalBaseURI;
	}
	
	function initWidgetSearch()
	{
		window.widgetSeeker = new WidgetSeeker(10, function () {
			
			var categories = widgetSeeker.categories;
			$('#categories > ul').empty();
			
			for (var i = 0; i < categories.length; i++)
			{
				var li = $('<li></li>');
				var a = $('<a href="#" id="searchForWidgets_' + categories[i].id + '">' + categories[i].category + '</a>');
				
				// We bind actions to the category link.
				a.click(function (event) {
					var id = this.id.substring(this.id.indexOf('_') + 1, this.id.length);
					id = (id == 'null') ? null : id;
					
					$('#categories > ul > li > a').removeClass('toggled');	
					$(this).addClass('toggled');
					
					widgetSeeker.reset(id);
					buildSearchedWidgetsResults(true);
				});
				
				$('#categories > ul').append(li.append(a));
			}
			
			// Now, we toggle the first category.
			if (widgetSeeker.categories.length)
			{
				var idCategory = widgetSeeker.categories[0].id;
				widgetSeeker.reset(idCategory);
				buildSearchedWidgetsResults(true);
				
				$('#categories > ul > li > a').eq(0).addClass('toggled');
			}
			
		});
	
		$('#next_widgets').click(function () {
			
			buildSearchedWidgetsResults(true);
		});
		
		$('#previous_widgets').click(function () {
			
			buildSearchedWidgetsResults(false);
		});
	}
	
	function buildSearchedWidgetsResults(prevOrNext)
	{	
		var func = function(widgets) {
						
			$('#results > ul').empty();
			
			for (j = 0; j < widgets.length; j++)
			{
				var li = $('<li id="addWidget_' + widgets[j].id + '"></li>');
				var div  = $('<div>' + widgets[j].name + '</div>');
				
				// Now we have to bind a click action to the list items
				// in order to provide a way to add the widget to the wall.
				li.click(function (event) {
					var widgetId = this.id.substring(this.id.indexOf('_') + 1, this.id.length);
					addWidget(widgetId);
					tb_remove();
				});
				
				$('#results > ul').append(li.append(div));
			}
						
		};
		
		if (prevOrNext == true)
			widgetSeeker.next(func);
		else
			widgetSeeker.previous(func);
	}